package ac.neec.data;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.List;

public class HeartRate implements Serializable{
        public List<Integer> heartRates;
        public byte[] bytes;

        public HeartRate() {
                heartRates = new ArrayList<Integer>();
        }

        public HeartRate(byte[] bytes) {
                heartRates = deserialize(bytes);
        }

        public void addHeartRate(int value) {
                heartRates.add(value);
        }

        public List<Integer> getHeartRates() {
                return heartRates;
        }
        public byte[] getHeartRatesBytes(){
                return serialize(heartRates);
        }

        public int getRestingHeartRate(){
                int value = 0;
                for (Integer item : heartRates) {
                        value += item;
                }
                return value / heartRates.size();
        }

        private List<Integer> deserialize(byte[] bytes) {
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois;
                List<Integer> obj = null;
                try {
                        ois = new ObjectInputStream(bais);
                        obj = (List<Integer>) ois.readObject();
                } catch (StreamCorruptedException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                }
                return obj;
        }

        private byte[] serialize(List<Integer> list) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos;
                byte[] array = null;
                try {
                        oos = new ObjectOutputStream(baos);
                        oos.writeObject(list);
                        array = baos.toByteArray();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                return array;
        }
}